#include <arpa/inet.h>
#include <iostream>
#include <cstring>

#include "InetAddress.h"

InetAddress::InetAddress(uint32_t ip_host, uint16_t port_host){
    addr_.sin_family = AF_INET;
    addr_.sin_port = htons(port_host);
    addr_.sin_addr.s_addr = htonl(ip_host);
}
InetAddress::InetAddress(uint16_t port_host) {
    bzero(&addr_, sizeof(addr_));
    addr_.sin_family = AF_INET;
    addr_.sin_port = htons(port_host);
}
InetAddress::InetAddress(StringPiece ip, uint16_t port_host) {
    addr_.sin_family = AF_INET;
    addr_.sin_port = htons(port_host);
    in_addr_t ip_net = inet_addr(ip.data());
    if (ip_net == INADDR_NONE) {
        std::cout << "stringpiece ip to InetAddresss fail" << std::endl;
        abort();
    }
    addr_.sin_addr.s_addr = ip_net;
}

sockaddr* InetAddress::getSockAddr() {
    return (sockaddr*)&addr_;
}

string InetAddress::toString() {
    string str = inet_ntoa(addr_.sin_addr);
    str += ":";
    str += std::to_string(ntohs(addr_.sin_port));
    return str;
}



